import { Injectable } from '@angular/core';
import { Hero } from '../../domain/entities';

import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/toPromise';


@Injectable()
export class HeroService {

  // private api_url = 'http://127.0.0.1:3000/heroes';
  private api_url = 'http://123.57.149.73:3000/heroes';
  private headers = new Headers({ 'Content-Type': 'application/json' });

  constructor(private http: Http) { }

  // GET /heroes
  getHeroes(): Promise<Hero[]> {
    const url = `${this.api_url}`;
    return this.http.get(url)
      .toPromise()
      .then(res => res.json() as Hero[])
      .catch(this.handleError);
  }

  // create 用 post
  // update 用 put
  save(hero: Hero): Promise<Hero> {
    if (hero.id === 0) {
      const url = `${this.api_url}`;
      return this.http.post(url, JSON.stringify(hero), { headers: this.headers })
        .toPromise()
        .then(() => hero)
        .catch(this.handleError);
    } else {
      const url = `${this.api_url}/${hero.id}`;
      return this.http.put(url, JSON.stringify(hero), { headers: this.headers })
        .toPromise()
        .then(() => hero)
        .catch(this.handleError);
    }
  }

  delete(id: number): Promise<any> {
    if (id > 0) {
      const url = `${this.api_url}/${id}`;
      return this.http.delete(url, { headers: this.headers })
        .toPromise()
        .then((response) => response)
        .catch(this.handleError);
    }
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }
}
